package order;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import oims.OrderRecord;
import oims.OrderRecordItem;

public class OrderServlet extends HttpServlet {

	/* (非 Javadoc)
	 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		perform(req, resp);
	}

	/* (非 Javadoc)
	 * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		perform(req, resp);
	}

	private void perform(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		HttpSession session = req.getSession();

		@SuppressWarnings("unchecked")
		ArrayList<OrderRecordItem> items =
				(ArrayList<OrderRecordItem>)session.getAttribute("items");
		Order order = (Order)session.getAttribute("order");

		OrderRecord orec = new OrderRecord();
		String[] orders = orec.order(	order.getCustomer(),
													new Date(order.getDate().getTime()),
													items.toArray(new OrderRecordItem[0]));
		session.removeAttribute("order");
		session.removeAttribute("items");

		req.setAttribute("msg",
				(orders == null) ? "受注できませんでした。" : "受注しました。");

		RequestDispatcher disp = req.getRequestDispatcher("/order/index.jsp");
		disp.forward(req, resp);
	}
}
